<!--
  Copyright 2018 Google LLC

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<link rel="import" href="../../bower_components/paper-checkbox/paper-checkbox.html">
<link rel="import" href="../../bower_components/paper-dropdown-menu/paper-dropdown-menu.html">
<link rel="import" href="../../bower_components/paper-input/paper-input.html">
<link rel="import" href="../../bower_components/paper-input/paper-textarea.html">
<link rel="import" href="../../bower_components/paper-item/paper-item.html">
<link rel="import" href="../../bower_components/paper-listbox/paper-listbox.html">
<link rel="import" href="../../bower_components/paper-menu-button/paper-menu-button.html">
<link rel="import" href="../../bower_components/paper-tooltip/paper-tooltip.html">
<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../../components/common/ajax-dialog/ajax-dialog.html">
<link rel="import" href="../../components/common/if-else/if-else.html">

<dom-module id="edit-form">
  <link rel="import" href="../technology/technology.css" type="css">
  <template>
    <style>
      /* local DOM styles go here */
      :host {
        display: block;
      }

      :host ajax-dialog > * {
        display: block;
        margin: 8px 0px;
      }

      :host .error {
        text-align: left;
        color: #ca4545;
        display: block;
        font-weight: bold;
        padding: 10px 0px;
      }

      .inline {
        display: flex;
      }

      .inline > * {
        flex: 1;
      }

      .inline.narrow > * {
        width: 350px;
        margin: 0 5px;
      }

      #file {
        --paper-input-container-input: {
          font-size: 12px;
        };

        --paper-input-container-underline: {
          display: none;
        };

        --paper-input-container-underline-focus: {
          display: none;
        };

        --paper-input-container-underline-disabled: {
          display: none;
        };
      }

      .job-select {
        padding: 0;
      }

      .job-checkbox {
        padding: 0.5em;
        display: block;
      }
    </style>
    <ajax-dialog
        id="dialog"
        url="[[fieldValues.uploadInfo.url]]"
        title="Edit or upload fuzzer"
        content-type=""
        on-before-submit="computeGcsBody"
        submit-button="Submit"
        response="{{response}}"
        on-response="handleGcsResponseAndError"
        opened="{{opened}}">
      <template is="dom-if" if="[[error]]">
        <div class="error">
          ERROR: [[error.response.message]]
        </div>
      </template>
      <div class="inline narrow">
        <paper-input
            label="Name"
            value="{{fuzzer.name}}"
            readonly="[[nameIsReadOnly(create)]]"
            title="Name of fuzzer. Allowed characters include letters, numbers, dashes and underscores.">
        </paper-input>
      </div>
      <div class="inline narrow">
        <paper-menu-button
            class="job-select"
            no-animations="true"
            ignore-select="true"
            noink>
          <div slot="dropdown-trigger">
            <paper-input
                readonly
                label="Select/modify jobs"
                title="Set of jobs to run with this fuzzer.">
              <iron-icon icon="paper-dropdown-menu:arrow-drop-down" suffix slot="suffix"></iron-icon>
            </paper-input>
          </div>
          <paper-listbox
              slot="dropdown-content"
              multi slot="dropdown-content"
              attr-for-selected="value"
              selected-values="{{fuzzer.jobs}}"
              selected-attribute="checked">
            <template is="dom-repeat" items="[[fieldValues.jobs]]">
              <paper-checkbox class="job-checkbox" value="[[item]]">
                [[item]]
              </paper-checkbox>
            </template>
          </paper-listbox>
        </paper-menu-button>
      </div>
      <div class="inline narrow">
        <paper-dropdown-menu
            no-animations="true"
            label="Corpus"
            title="Corpus to run this fuzzer with"
            noink>
          <paper-listbox slot="dropdown-content" attr-for-selected="value" selected="{{fuzzer.data_bundle_name}}">
            <paper-item value="">None</paper-item>
            <template is="dom-repeat" items="[[fieldValues.corpora]]">
              <paper-item value="[[item]]">[[item]]</paper-item>
            </template>
          </paper-listbox>
        </paper-dropdown-menu>
      </div>
      <div class="inline narrow">
        <paper-input id="file" type="file" value="{{file}}" label="Fuzzer archive"></paper-input>
      </div>
      <div class="inline narrow">
        <paper-input
            label="Script path (optional)"
            value="{{fuzzer.executable_path}}"
            title="Relative path to main file that executes fuzzer. If not provided, uses the first file with 'run' in name.">
        </paper-input>
      </div>
      <div class="inline narrow">
        <paper-input
            label="Launcher path (optional)"
            value="{{fuzzer.launcher_script}}"
            title="Relative path to wrapper script that executes application. Executed as: <launcher_path> <app_path> <app_args>">
        </paper-input>
      </div>
      <div class="inline narrow">
        <paper-input
            type="number"
            label="Testcase timeout (optional)"
            value="{{fuzzer.timeout}}"
            title="Time in seconds to run a testcase for. If provided, this overrides TEST_TIMEOUT defined in jobs.">
        </paper-input>
      </div>
      <div class="inline narrow">
        <paper-input
            type="number"
            label="Max generated testcases (optional)"
            value="{{fuzzer.max_testcases}}"
            title="Upper limit on number of testcases generated. If provided, this overrides MAX_TESTCASES defined in jobs.">
        </paper-input>
      </div>
      <div class="inline narrow">
        <paper-textarea
            label="Environment variables (a=b, one per line)"
            value="{{fuzzer.additional_environment_string}}"
            on-input="envVarsChanged"
            title="Additional environment variables. If provided, these variables override ones defined in jobs.">
        </paper-textarea>
      </div>
      <div class="inline narrow">
        <paper-checkbox checked="{{fuzzer.external_contribution}}">External contribution</paper-checkbox>

        <!-- TODO: Re-enable after the differential fuzzing is implemented.
        <paper-checkbox checked="{{fuzzer.differential}}">Differential fuzzer</paper-checkbox>
        -->
      </div>
    </ajax-dialog>
    <iron-ajax
      id="ajaxFinish"
      url="/fuzzers/edit"
      method="POST"
      content-type="application/json"
      last-error="{{error}}"
      on-response="handleFinishResponse"
      debounce-duration="1000">
    </iron-ajax>
  </template>
  <script>
    class EditForm extends Polymer.Element {
      static get is() { return 'edit-form'; }

      static get properties() {
        return {
          fuzzer: Object,
          paramKeys: {
            type: Array,
            value: [
                'additional_environment_string',
                'data_bundle_name',
                'differential',
                'executable_path',
                'external_contribution',
                'jobs',
                'launcher_script',
                'max_testcases',
                'name',
                'timeout',
            ],
          },
          file: Object,
          response: Object,
          opened: {
            type: Boolean,
            notify: true
          },
          fieldValues: Object,
          create: Boolean,
        };
      }

      sendFinishRequest() {
        if (this.create) {
          this.$.ajaxFinish.url = '/fuzzers/create';
        } else {
          this.$.ajaxFinish.url = '/fuzzers/edit';
        }

        this.computeFinishBody();
        this.$.ajaxFinish.generateRequest();
      }

      computeGcsBody() {
        let uploadData = new FormData();
        uploadData.append('bucket', this.fieldValues.uploadInfo.bucket);
        uploadData.append('key', this.fieldValues.uploadInfo.key);
        uploadData.append('GoogleAccessId', this.fieldValues.uploadInfo.google_access_id);
        uploadData.append('policy', this.fieldValues.uploadInfo.policy);
        uploadData.append('signature', this.fieldValues.uploadInfo.signature);

        let file = this.$.file.inputElement.inputElement.files[0];
        if (file) {
          uploadData.append('x-goog-meta-filename', file.name);
          uploadData.append('file', file);
        } else {
          this.sendFinishRequest();
          return;
        }

        this.$.dialog.$.ajax.body = uploadData;
      }

      computeFinishBody() {
        if (!this.fuzzer)
          return;

        let request = {
          'csrf_token': this.fieldValues.csrfToken,
        };

        for (let key of this.paramKeys) {
          if (this.fuzzer[key]) {
            request[key] = this.fuzzer[key];
          }
        }

        if (!this.create)
          request['key'] = this.fuzzer.id;

        if (this.file) {
          request['upload_key'] = this.fieldValues.uploadInfo.key;
        }
        this.$.ajaxFinish.body = request;
      }

      handleGcsResponseAndError(ev) {
        this.sendFinishRequest();
      }

      handleFinishResponse(ev) {
        window.location.href = '/fuzzers';
      }

      nameIsReadOnly(create) {
        return !create;
      }
    }

    customElements.define(EditForm.is, EditForm);
  </script>
</dom-module>

